//
//  DetailViewController.m
//  VMIX
//
//  Created by jeffs on 5/14/10.
//  Copyright VMIX Media Inc. 2010. All rights reserved.
//

#import "DetailViewController.h"
#import "RootViewController.h"
#import "VmixGridViewController.h"
#import "VMIXAppDelegate.h"



@interface DetailViewController ()
@property (nonatomic, retain) UIPopoverController *popoverController;
- (void)configureView;
@end



@implementation DetailViewController

@synthesize toolbar, popoverController, detailItem, detailDescriptionLabel, rootViewController, moviePlayerView, rootViewFrame, detailViewFrame, currentVideo;
@synthesize videoTitle, descriptionText, uploadDate, theMoviePlayer, moviePlayerLoadingSpinner, oppQueue, playVideoOperation, moviePlayerPortraitView;

#pragma mark -
#pragma mark Object insertion

- (IBAction)insertNewObject:(id)sender {
	
	[rootViewController insertNewObject:sender];	
}


#pragma mark -
#pragma mark Managing the detail item

/*
 When setting the detail item, update the view and dismiss the popover controller if it's showing.
 */
- (void)setDetailItem:(NSManagedObject *)managedObject {
    
	if (detailItem != managedObject) {
		[detailItem release];
		detailItem = [managedObject retain];
		
        // Update the view.
        [self configureView];
	}
    
    if (popoverController != nil) {
        [popoverController dismissPopoverAnimated:YES];
    }		
}


- (void)configureView {
    // Update the user interface for the detail item.
    detailDescriptionLabel.text = [[detailItem valueForKey:@"timeStamp"] description];
}

- (void)loadVideo:(VmixVideo *) video {
    
	if ([self.popoverController isPopoverVisible]) {
		[self.popoverController dismissPopoverAnimated:YES];
	}

	[self.theMoviePlayer stop];
	self.theMoviePlayer.shouldAutoplay = YES;
	self.currentVideo = video;
	self.descriptionText.text = self.currentVideo.description;
	self.videoTitle.text = self.currentVideo.title;
	NSDateFormatter *df = [[NSDateFormatter alloc] init];
	[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
	NSDate *myDate = [df dateFromString: self.currentVideo.date_created];
	[df setDateFormat:@"MMM d, yyyy 'at' h:mm a"];
	self.uploadDate.text = [NSString stringWithFormat:@"Uploaded on %@", [df stringFromDate:myDate] ];

	self.moviePlayerLoadingSpinner.hidden = NO;
	[self.moviePlayerLoadingSpinner startAnimating];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	//Setup operation queue to spin up non blocking execution thread.
	self.playVideoOperation = [[PlayVideoOperation alloc] init];
	self.playVideoOperation.playApi = [NSString stringWithFormat:@"%@token=%@&output=xml", PLAY, self.currentVideo.token ];
	self.playVideoOperation.delegate = self;
	[oppQueue addOperation:self.playVideoOperation];
	[self.playVideoOperation release];
	
	
	
}

// handle MPMoviePlayerLoadStateChangeNotification
- (void)movieLoadStateChanged:(NSNotification* )notification {
	
	// check the state to see if the player should be playable
	if( self.theMoviePlayer.loadState == MPMovieLoadStatePlayable ) {
		
		// stop the spinner
		[self.moviePlayerLoadingSpinner stopAnimating];
	}

}

#pragma mark -
#pragma mark Split view support

- (void)splitViewController: (UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController: (UIPopoverController*)pc {
    
    barButtonItem.title = @"Videos";
    NSMutableArray *items = [[toolbar items] mutableCopy];
    [items insertObject:barButtonItem atIndex:0];
    [toolbar setItems:items animated:YES];
    [items release];
    self.popoverController = pc;
	if(self.theMoviePlayer == nil){
		self.theMoviePlayer = [[MPMoviePlayerController alloc] init];	
		self.theMoviePlayer.view.frame = self.moviePlayerView.bounds;
		self.theMoviePlayer.shouldAutoplay = YES;
		self.theMoviePlayer.scalingMode = MPMovieScalingModeAspectFit;
		[self.moviePlayerView addSubview:self.theMoviePlayer.view];
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(movieLoadStateChanged: ) 
													 name:MPMoviePlayerLoadStateDidChangeNotification 
												   object:self.theMoviePlayer]; 
	}
	if(self.oppQueue == nil){
		self.oppQueue = [[NSOperationQueue alloc] init];
	}
	
	self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_center_large.png"]];

}


// Called when the view is shown again in the split view, invalidating the button and popover controller.
- (void)splitViewController: (UISplitViewController*)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem {
    
    NSMutableArray *items = [[toolbar items] mutableCopy];
    [items removeObjectAtIndex:0];
    [toolbar setItems:items animated:YES];
    [items release];
    self.popoverController = nil;
	self.rootViewController.navigationItem.rightBarButtonItem = self.rootViewController.rightArrowButton;
	
	if(self.theMoviePlayer == nil){
		self.theMoviePlayer = [[MPMoviePlayerController alloc] init];	
		self.theMoviePlayer.view.frame = self.moviePlayerView.bounds;
		self.theMoviePlayer.shouldAutoplay = YES;
		self.theMoviePlayer.scalingMode = MPMovieScalingModeAspectFit;
		[self.moviePlayerView addSubview:self.theMoviePlayer.view];
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(movieLoadStateChanged:) 
													 name:MPMoviePlayerLoadStateDidChangeNotification 
												   object:self.theMoviePlayer]; 
	}
	if(self.oppQueue == nil){
		self.oppQueue = [[NSOperationQueue alloc] init];
	}
	
	
	self.rootViewFrame = self.rootViewController.navigationController.view.frame;
	self.detailViewFrame = self.view.frame;
	
	self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_center_large.png"]];
	
	
}




#pragma mark -
#pragma mark Rotation support

// Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}


- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
	
	switch (interfaceOrientation) {
		case UIInterfaceOrientationPortrait:
			//[self.theMoviePlayer.view removeFromSuperview];
			self.theMoviePlayer.view.frame = self.moviePlayerView.bounds;
			self.rootViewController.navigationItem.rightBarButtonItem = nil;
			//[self.moviePlayerView addSubview:self.theMoviePlayer.view];
			break;
		case UIInterfaceOrientationPortraitUpsideDown:
			//[self.theMoviePlayer.view removeFromSuperview];
			self.theMoviePlayer.view.frame = self.moviePlayerView.bounds;
			self.rootViewController.navigationItem.rightBarButtonItem = nil;
			//[self.moviePlayerView addSubview:self.theMoviePlayer.view];
			break;
		case UIInterfaceOrientationLandscapeLeft:
			//[self.theMoviePlayer.view removeFromSuperview];
			self.theMoviePlayer.view.frame = self.moviePlayerView.bounds;
			//[self.moviePlayerView addSubview:self.theMoviePlayer.view];
			break;
		case UIInterfaceOrientationLandscapeRight:
			//[self.theMoviePlayer.view removeFromSuperview];
			self.theMoviePlayer.view.frame = self.moviePlayerView.bounds;
			//[self.moviePlayerView addSubview:self.theMoviePlayer.view];
			break;
		default:
			break;
	}
	
	
}


#pragma mark -
#pragma mark View lifecycle

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

/*
 - (void)viewWillAppear:(BOOL)animated {
 [super viewWillAppear:animated];
 }
 */
/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */

- (void)didFinishParsingPlayData:(NSURL *) playUrl{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	[self.theMoviePlayer performSelectorOnMainThread:@selector(setContentURL:)
										  withObject:playUrl
									   waitUntilDone:YES];
	
}

-(void) setMovieContent:(NSURL *) playUrl {
	[self.theMoviePlayer performSelectorOnMainThread:@selector(setContentURL:)
						   withObject:playUrl
						waitUntilDone:YES];
	//[self.theMoviePlayer setContentURL:playUrl];
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	self.popoverController = nil;
}

-(void) expandView {
	

	 [self.view.superview bringSubviewToFront:self.view];
	 [UIView beginAnimations:@"Animate View" context:nil];
	 [UIView setAnimationDuration:0.2f];
	 self.view.frame = CGRectMake(1024, 0, 1024, 768);
	 self.rootViewController.navigationController.view.frame = CGRectMake(0, 0, 1024, 768);
	 [UIView commitAnimations];
	[self.rootViewController.navigationController pushViewController:self.rootViewController.gridViewController  animated:NO];
	[self.theMoviePlayer pause];
}




- (void) collapseView {
	
	[self.view.superview bringSubviewToFront:self.view];
	[UIView beginAnimations:@"Animate View" context:nil];
	[UIView setAnimationDuration:0.2f];
	self.rootViewController.navigationController.view.frame = self.rootViewFrame;
	self.view.frame = self.detailViewFrame;
	[UIView commitAnimations];

	[self.rootViewController.navigationController popViewControllerAnimated:NO];
	[self.theMoviePlayer play];



}
  


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
	
    [popoverController release];
    [toolbar release];
	
	[detailItem release];
	[detailDescriptionLabel release];
    
	[super dealloc];
}	


@end
